package com.panvan.android;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

public class WebViewInputCamera {

    /**
     * 拍照
     */
    WebView webview;
    AppCompatActivity activity;
    WebViewChromeListener webViewChromeListener;
    WebViewInputCamera(MainActivity activity,WebView webview){
        this.activity=activity;
        this.webview=webview;
        this.webViewChromeListener=new WebViewChromeListener(activity);
        this.webview.setWebChromeClient(this.webViewChromeListener);
    }

    /**
     * 创建 webView 打开照相机
     * @return
     */
    public ActivityResultLauncher<Intent> createCameraLauncher(){
        return  this.activity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode()!=0) {
                   webViewChromeListener.uploadMessage.onReceiveValue(new Uri[]{webViewChromeListener.imageUri});
                } else {
                    webViewChromeListener. uploadMessage.onReceiveValue(new Uri[]{});
                }
                webViewChromeListener. uploadMessage = null;
            }
        });
    }
    /**
     * 创建 webView 打开文件选择
     * @return
     */
    public ActivityResultLauncher<Intent> createCheckFileLauncher(){
        return  this.activity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult res) {
                try {
                    Uri result = res.getData() == null || res.getResultCode() != activity.RESULT_OK ? null :
                            res.getData().getData();
                    webViewChromeListener.uploadMessage.onReceiveValue(new Uri[]{result});
                    webViewChromeListener.uploadMessage = null;
                } catch (Exception e) {
                    webViewChromeListener.uploadMessage = null;
                }
            }
        });
    }

}
